'''
Created on Mar 6, 2010

@author: Nick Heiner
'''
from google.appengine.ext import db
from Utils import render
from BaseHandler import BaseHandler
from Add import AddToCart

class Detail(BaseHandler):
    
    toRender = None
    
    def body(self):
        CSIN = self.request.get("CSIN")
        try:
            CSIN = int(CSIN)
        except ValueError:
            CSIN = None
        
        if CSIN:
            quantity = self.request.get("quantity") 
            if quantity:
                cartAdder = AddToCart(CSIN=CSIN, quantity=quantity, user=self.user)
                if not self.user:
                    cartAdder.anon_key = self.anon_key
                
                errors = cartAdder.validateInput()
                if errors:
                    self.add_message("No items added to cart.", self.MSG_WARNING)
                    for error in errors:
                        self.add_message(error, self.MSG_ERROR)
                else:         
                    messages = cartAdder.add(self.ANON_CART_TIMEOUT)
                    if messages:
                        for msg in messages:
                            self.add_message(msg, self.MSG_NOTICE)
            
            item = db.GqlQuery("SELECT * FROM Item WHERE CSIN = :1", CSIN).get()
            if item:
                def toRender(): # so we can call it later, after the messages are printed
                    
                    attrs = [{'name': 'Name', 'value': item.name},
                             {'name': 'Price', 'value': '$%d' % item.price},
                             {'name': 'Quantity available', 'value': item.quantity},
                             ]
                    
                    render('Views/item_detail.html', self, {'attributes': attrs,
                                                            'table_name': item.name,
                                                            'review': item.review,
                                                            'image': item.image,
                                                            })
                    # disable the button for items that are out of stock. untested.
                    render('Views/add_to_cart_form.html', self, {'CSIN': CSIN, 'disabled': item.quantity <= 0})
                self.toRender = toRender
            else:
                self.add_message('The item with CSIN %d could not be found' % CSIN, self.MSG_ERROR) 
        else:
            self.add_message('No valid CSIN supplied.', self.MSG_ERROR) 
              
        self.header("Item Detail Page", self.DETAIL)
        if self.toRender:
            self.toRender()
        self.footer()  